package org.example.kafka.commit;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.example.kafka.common.CommonConstant;
import org.example.kafka.common.KafkaConstants;

import java.util.Collections;
import java.util.Properties;

/**
 * 同步和异步集合
 */
public class SyncAndAsync {
    public static void main(String[] args) {
        /*消息消费者*/
        Properties properties = KafkaConstants.consumerConfig("SyncAndAsync",
                StringDeserializer.class,
                StringDeserializer.class);
        // 取消自动提交
        properties.put("enable.auto.commit",false);
        // 创建消息的消费者
        KafkaConsumer<String,String> consumer
                = new KafkaConsumer<String, String>(properties);
        try{
            // 消费者开始订阅主题
            consumer.subscribe(Collections.singletonList(CommonConstant.CONSUMER_COMMIT_TOPIC));
            while(true) {
                ConsumerRecords<String, String> records
                        = consumer.poll(500);
                for (ConsumerRecord<String, String> record : records) {
                    System.out.println(String.format(
                            "主题：%s，分区：%d，偏移量：%d，key：%s，value：%s",
                            record.topic(), record.partition(), record.offset(),
                            record.key(), record.value()));
                    //do our work
                }
                consumer.commitAsync();
            }
        }catch (Exception e){
            System.out.println("Commit failed:");
            e.printStackTrace();
        }finally {
            try {
                // 同步提交
                consumer.commitSync();
            } finally {
                consumer.close();
            }
        }



    }
}
